package JDBC;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class tset {
    public static void main(String[] args) throws SQLException {
        //Scanner scanner = new Scanner(System.in);
        //System.out.println("请输入id：");
        //int id = scanner.nextInt();
        //System.out.println("请输入name：");
        //String name = scanner.next();
        //1.创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/students?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("root");
        //2.和数据库服务器建立网络连接
        Connection connection = dataSource.getConnection();
        //System.out.println(connection);

        //3.构造sql语句
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        //statement.setInt(1,id);
        //statement.setString(2,name);
        //4.把sql发送到服务器上执行
        //int n = statement.executeUpdate();
        //System.out.println(n);

        ResultSet resultSet = statement.executeQuery();

        while(resultSet.next()) {
            System.out.print(resultSet.getInt("id") + " ");
            System.out.println(resultSet.getString("name"));
        }
        //5.释放上述资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
